package com.jinbiao.quasar.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.jinbiao.quasar.annotate.OperationLog;
import com.jinbiao.quasar.model.SysApi;
import com.jinbiao.quasar.util.AjaxJson;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.extend.sqltoy.annotation.Db;
import org.sagacity.sqltoy.dao.SqlToyLazyDao;
import org.sagacity.sqltoy.model.EntityQuery;
import org.sagacity.sqltoy.model.Page;

import java.util.List;

@Controller
@OperationLog
public class ApiController {
    @Db
    SqlToyLazyDao dao;
    @Mapping("/api/get-api-list")
    public AjaxJson getApiList(int page,int pageSize,String sortBy,boolean desc){
        EntityQuery entityQuery = EntityQuery.create().where("#[and api_group like :apiGroup]\n" +
                "            #[and api_method like :apiMethod]\n" +
                "            #[and api_path like :apiPath]");
        Page<SysApi> pageResult =  dao.findPageEntity(new Page(pageSize,page),SysApi.class, desc?entityQuery.orderByDesc(sortBy):entityQuery.orderBy(sortBy),SysApi.class);
        return AjaxJson.getSuccessData(pageResult);
    }

    @Mapping("/api/delete-api-by-id")
    public AjaxJson deleteApiById(SysApi sysApi){
        return AjaxJson.getSuccessData(dao.delete(sysApi));
    }

    @Mapping("/api/edit-api")
    public AjaxJson editApi(SysApi sysApi){
        return AjaxJson.getSuccessData(dao.saveOrUpdate(sysApi));
    }

    @Mapping("/api/add-api")
    public AjaxJson addApi(SysApi sysApi){
        return AjaxJson.getSuccessData(dao.saveOrUpdate(sysApi));
    }

    @Mapping("/api/query-api-by-id")
    public AjaxJson queryApiById(SysApi sysApi){
        List<SysApi> results = dao.findBySql("sysApiList",sysApi);
        if(CollectionUtil.isNotEmpty(results)){
            SysApi api = results.get(0);
            return AjaxJson.getSuccessData(api);
        }
        return AjaxJson.getSuccessData(null);
    }

    @Mapping("/public/get-api-all")
    public AjaxJson getApiAll(SysApi sysApi){
        return AjaxJson.getSuccessData(dao.findBySql("sysApiList",sysApi));
    }
}
